﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using OnlineManagement.Model;
using OnlineManagement.BLL;
namespace OnlineManagement.Web.WebServices
{
    /// <summary>
    /// Summary description for Sows
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    [ScriptService]
    public class Sows : System.Web.Services.WebService
    {

        [WebMethod(EnableSession = true)]
        public List<Model.Sow> GetSows(int hoggeryId) {
            List<Model.Sow> sows = new List<Model.Sow>();
            Model.Sow sow = new Model.Sow();
            sow.SowID = Guid.NewGuid();
            sow.BitID = "12345";
            sow.PigPenName = "2栋1号";
            sows.Add(sow);
            return sows;
        }

        [WebMethod(EnableSession = true)]
        public JsonMsg AddSow(string hoggeryIDStr, string bitIDStr, 
            string TypeIDStr, string SourceIDStr, string DateInFarmStr, 
            string PigPenIDStr, string hybridizationCountStr, 
            string propagateCountStr, string propagateStateIDStr, string comment)
        {
            JsonMsg msg = null;
            int hoggerID;
            Guid typeID;
            int sourceID;
            Guid pigPendID;
            int hybridizationCount;
            int propagateCount;
            Guid propagateStateID;

            if (!int.TryParse(hoggeryIDStr, out hoggerID)
                || string.IsNullOrEmpty(bitIDStr)
                || !Guid.TryParse(TypeIDStr, out typeID)
                || !int.TryParse(SourceIDStr, out sourceID)
                || !Guid.TryParse(PigPenIDStr, out pigPendID)
                || !int.TryParse(hybridizationCountStr, out hybridizationCount)
                || !int.TryParse(propagateCountStr, out propagateCount)
                || !Guid.TryParse(propagateStateIDStr, out propagateStateID)
                )
            {
                msg = new JsonMsg() { Flag = false, MessageId = "输入错误", Message = "您提交的数据中存在空值或者无效的数据，请重新输入." };
                return msg;
            }

            DateTime? dateInFarm = null;
            DateTime dateFarm;
            if (DateTime.TryParse(DateInFarmStr, out dateFarm))
            {
                dateInFarm = new Nullable<DateTime>(dateFarm);
            }

            try
            {
                BLL.Sow dllSow = new BLL.Sow();
                Model.Sow modelSow = new Model.Sow()
                {
                    HoggeryID = hoggerID,
                    BitID = bitIDStr,
                    TypeID = typeID,
                    SourceID = sourceID,
                    PigPenID = pigPendID,
                    HybridizationCount = hybridizationCount,
                    PropagateCount = propagateCount,
                    PropagateStateID = propagateStateID,
                    DateJoinFarm = dateInFarm,
                    Comment = comment
                };
                string message = string.Empty;
                //bool result= dllSow.Add(modelSow);
                string sowIdStr;
                bool result = dllSow.Add(modelSow, out message,out sowIdStr);
                msg = new JsonMsg() { Message = message };
                msg.Flag = result;
                
                log4net.ILog log = log4net.LogManager.GetLogger(new System.Diagnostics.StackFrame(0).GetMethod().Name);
                Com.HoggeryLog businessLog = new Com.HoggeryLog()
                {
                    HoggeryID = hoggerID,
                    PigId = sowIdStr,
                    BusinessLogDate = System.DateTime.Now,
                    LogType = OnlineManagement.Web.Com.HoggeryLogType.SowAdd,

                };
                if (result)
                {
                    businessLog.Message =string.Format("新加{0}号母猪",bitIDStr);
                }
                businessLog.LogComment = message;
                log.Info(businessLog);

            }
            catch (Exception)
            {
                msg = new JsonMsg() { Flag = false, MessageId = "服务器错误", Message = "服务器出现错误，请联系管理员。" };
            }
            return msg;
        }


        [WebMethod(EnableSession = true)]
        public JsonMsg DeleteSow(string sowId)
        {
            JsonMsg msg;
            Guid guid;
            try
            {
                if (Guid.TryParse(sowId, out guid))
                {
                    BLL.Sow bllSow = new BLL.Sow();
                    string message;
                    bool flag = bllSow.Delete(guid, out message);
                    msg = new JsonMsg() { Message = message };
                    msg.Flag = flag;
                    return msg;
                }

            }
            catch (Exception)
            {
                msg = new JsonMsg() { Flag = false, MessageId = "服务器错误", Message = "服务器出现错误，请联系管理员。" };
            }
            return msg = new JsonMsg() { Flag = false, MessageId = "输入错误", Message = "用户信息错误，请重新提交数据。" };
        }

        [WebMethod(EnableSession = true)]
        public JsonMsg UpdateSow(string sowId, string changedPigPenId, string hybridizationCount, string propagateCount, string propagateStateID, string comment)
        {
            Guid sowGuid;
            Guid pigPenGuid;
            Guid propagateStateGuid;
            int hybridization;
            int propagate;
            Model.Sow mSow = new Model.Sow();
            JsonMsg msg;
           

            if (Guid.TryParse(sowId, out sowGuid)
                && Guid.TryParse(propagateStateID, out propagateStateGuid)
                &&Guid.TryParse(changedPigPenId, out pigPenGuid))
            {
                mSow.SowID = sowGuid;
                mSow.PropagateStateID = propagateStateGuid;
                mSow.Comment = comment;
            }
            else {
                msg = new JsonMsg() { Flag = false, MessageId = "输入错误", Message = "您提交的数据中存在空值或者无效的数据，请重新输入." };
                return msg;
            }
            mSow.PigPenID = Guid.TryParse(changedPigPenId, out pigPenGuid) ? pigPenGuid : Guid.NewGuid();

            if (int.TryParse(hybridizationCount, out hybridization))
            {
                mSow.HybridizationCount = hybridization;
            }
            if (int.TryParse(propagateCount, out propagate))
            {
                mSow.PropagateCount = propagate;
            }
            try
            {
                BLL.Sow bSow = new BLL.Sow();
                string message;
                bool result = bSow.Update(mSow, out message);
                msg = new JsonMsg() {Flag=result,Message=message};
            }catch(Exception){
                msg = new JsonMsg() { Flag = false,  Message =OnlineManagement.Common.PubConstant.ServerError };
            }
            return msg;
        }


        /// <summary>
        /// 母猪发情
        /// </summary>
        /// <param name="hoggeryId"></param>
        /// <param name="sowId"></param>
        /// <param name="faqingDate"></param>
        /// <param name="sowDayOld"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public JsonMsg SowFaQingAddOrUpdate
            (int hoggeryId, Guid sowId, DateTime faqingDate, 
            string sowDayOld, string sowFaQingWeight, string comment)
        {
            JsonMsg msg = null;
            try
            {
                if(!HttpContext.Current.User.Identity.IsAuthenticated){
                    msg = new JsonMsg() { Flag=false, Message=Common.PubMsg.NotLogin };
                    return msg;
                }
                
                Model.FaQingRecord record = new Model.FaQingRecord()
                {
                    HoggeryId = hoggeryId,
                    SowId =sowId,
                    FaQingDate = faqingDate,
                    Comment = comment
                };
                int sowOld;
                float weight;
                int.TryParse(sowDayOld, out sowOld);
                float.TryParse(sowFaQingWeight, out weight);
                record.SowDayOld = sowOld;
                record.SowFaQingWeight = weight;

                BLL.FaQingRecord BllFaQing = new BLL.FaQingRecord();
                string returnValue = string.Empty;
                bool result = BllFaQing.SowFaQingAddOrUpdate(record, out returnValue);
                msg = new JsonMsg() { Flag = result, Message = returnValue };


                log4net.ILog log = log4net.LogManager.GetLogger(new System.Diagnostics.StackFrame(0).GetMethod().Name);
                Com.HoggeryLog businessLog = new Com.HoggeryLog()
                {
                    HoggeryID = hoggeryId,
                    PigId = sowId.ToString(),
                    BusinessLogDate = System.DateTime.Now,
                    LogType = OnlineManagement.Web.Com.HoggeryLogType.FaQingRecord,

                };
                if (result)
                {
                    businessLog.Message = "成功添加母猪发情记录";
                }
                else {
                    businessLog.Message = "母猪发情记录登记失败";
                }
                businessLog.LogComment = returnValue;
                log.Info(businessLog);

                return msg;
            }catch(Exception ex){
                msg = new JsonMsg() { Flag = false, Message = OnlineManagement.Common.PubConstant.ServerError };
                return msg;
            }
        }

       

    }
}
